package org.jiamandan.com.config;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageDecoder;

import java.util.List;

public class DatagramPacketToHexDecoder extends MessageToMessageDecoder<DatagramPacket> {

    @Override
    protected void decode(ChannelHandlerContext ctx, DatagramPacket packet, List<Object> out) {
        ByteBuf content = packet.content().retain(); // 保留引用防止释放
        try {
            String hex = byteBufToHex(content);    // 转换为 HEX 字符串
            out.add(new UdpHexMessage(hex, packet.sender(),packet));
        } finally {
            content.release(); // 确保释放 ByteBuf
        }
    }

    //将 ByteBuf 转换为 HEX 字符串
    private String byteBufToHex(ByteBuf buffer) {
        StringBuilder hexString = new StringBuilder();
        while (buffer.isReadable()) {
            byte b = buffer.readByte();
            hexString.append(String.format("%02X", b)); // 大写 HEX，小写用 "%02x"
        }
        return hexString.toString();
    }
}